import { PlusOutlined, CloseCircleFilled } from '@ant-design/icons'
import { Button, Tooltip } from 'antd'
import { Empty } from '@/desktop/components'
import { ChooseAccountModal } from '@/desktop/components/ChooseAccount'
import  defaultAvatar  from '@/desktop/assets/avatar.jpg'
import type { BaseAccount } from '@/services/auth'
import './Accounts.module.less'

export default function Accounts(props: {
  all: BaseAccount[]
  ids: string[]
  onAdd: (ids: string[]) => void
  onRemove: (ids: string[]) => void
}) {
  const { all, ids, onAdd, onRemove } = props
  const accountMap = useMemo(() => new Map(all.map(v => [v.id, v])), [all])

  const [adding, setAdding] = useState(false)
  const startAdd = useCallback(() => setAdding(true), [])
  const cancelAdd = useCallback(() => setAdding(false), [])
  const finishAdd = useCallback(
    (accounts: BaseAccount[]) => {
      setAdding(false)
      onAdd([...ids, ...accounts.map(acc => acc.id)])
    },
    [ids, onAdd],
  )

  return <div styleName="accounts-wrap">
    <header>
      <label>分组下账号</label>
      <Button size="small" icon={<PlusOutlined />} type="primary" onClick={startAdd}>
        添加账号
      </Button>
    </header>

    {ids.length ? (
      <div styleName="accounts">
        {ids.map(id => <AccountItem
          key={id}
          item={accountMap.get(id) ?? id}
          onRemove={onRemove}
        />)}
      </div>
    ) : (
      <div styleName="empty-accounts">
        <Empty description="分组下尚未添加账号" />
      </div>
    )}

    <ChooseAccountModal
      visible={!!adding}
      multiple={true}
      withGroups={false}
      lockChoosed={ids}
      onChoosed={finishAdd}
      onCancel={cancelAdd}
    />
  </div>
}

function AccountItem(props: { item: BaseAccount | string; onRemove: (ids: string[]) => void }) {
  const { item: raw, onRemove } = props
  const item = typeof raw === 'string' ? { avatar: '', remark: '', name: raw, id: raw } : raw

  return <div styleName="account">
    <img src={item.avatar || defaultAvatar} />
    <span styleName="name">
      {item.name}
      {item.remark ? <span styleName="remark">（{item.remark}）</span> : null}
    </span>
    <Tooltip title="移出分组" placement="right" color="#555">
      <CloseCircleFilled styleName="remove" onClick={() => onRemove([item.id])} />
    </Tooltip>
  </div>
}
